package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;
    /*
    orders {"remark":"xxxxxxxxxxxxxxxxxxx","payMethod":1,"addressBookId":"1599599207619375105"}
        id  number   status:1  user_id:BaseContext获取当前线程绑定用户id  order_time: new Date()    checkout_time: 不处理
        amout:总金额 通过计算获取到的   phone:收货人   address:收货地址，通过addressBookId在地址簿表中获取
        user_name:通过user_id查询用户表  consignee:收货人姓名  通过addressBookId查询到的


        order_detail
          获取当前用户购物车中的数据 select *from shopping_cart where user_id='xxxxxx'
         List<ShoppingCart> list=xxxx;

           定义总金额
           遍历list,ShoppingCart ,创建对象，为orderDetail赋予orderId ,将ShoppingCart复制到OrderDetail，
            计算各个购物项金额累加到总
           将orderDetail加入新的集合
    */
    //ctrl+i   implement
    @Override
    public void submit(Orders orders) {
        //{"remark":"xxxxxxxxxxxxxxxxxxx","payMethod":1,"addressBookId":"1599599207619375105"}
        //A. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据  select * from shoppping_cart where user_id='xxx'
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>(); //select * from shoppping_cart
        wrapper.eq(ShoppingCart::getUserId,userId);//where user_id='xxx'
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper); //当前用户购物车中的数据  9个商品信息
        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }
        //B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId); //{useID:"",phone:"xxx"}
        //C. 根据地址ID, 查询地址数据  {id user_id consignee sex phone detail label is_default}
        Long addressBookId = orders.getAddressBookId(); //select * from address_book where id='xx '
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        long orderId = IdWorker.getId();//订单号  mp内部工具获取ID
        //int money=0;
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> list=new ArrayList<>();
        //D. 组装订单明细数据, 批量保存订单明细
        for (ShoppingCart item : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            list.add(orderDetail);
        }
        //E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);  //ID
        orders.setNumber(String.valueOf(orderId));//订单编号
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(1);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);
        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(list);

        //清空购物车数据
        shoppingCartService.remove(wrapper);


    }
}